﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

namespace ITU.Yemekhane.TestApp
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private Action<string> redirectionCallback;
        private Action<List<string>> MorningCallback;
        private Action<List<string>> LaunchCallback;
        private string requestedDate;
        private bool isMorning;

        public static string MenuUrl = "http://www.sks.itu.edu.tr/index.php?option=com_jevents";
        public static string BaseUrl = "http://www.sks.itu.edu.tr";

        public void getMenu(DateTime Datetime, bool Morning, Action<List<string>> _mcallback, Action<List<string>> _lcallback)
        {
            this.MorningCallback = _mcallback;
            this.LaunchCallback = _lcallback;

            requestedDate = DateTime.Today.ToString("dd.MM.yyyy");
            isMorning = Morning;

            WebClient client = new WebClient();
            client.DownloadStringAsync(new Uri(MenuUrl));
            client.DownloadStringCompleted += client_DownloadStringCompleted;
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string htmlResult = e.Result;
            Regex aElementsWithClass = new Regex(@"<a class\b[^>]*>(.*?)</a>");
            Regex hrefAttribute = new Regex("href=\\\"(.*?)\\\"");
            MatchCollection regexCollection = aElementsWithClass.Matches(htmlResult);
            Dictionary<bool, string> urlDictionary = new Dictionary<bool, string>();
            foreach (Match item in regexCollection)
            {
                if (item.Value.Contains(requestedDate))
                {
                    bool _morning = true;
                    if (item.Value.Contains("9:01"))
                    {
                        _morning = true;
                    }
                    else
                    {
                        _morning = false;
                    }
                    Match attribute = hrefAttribute.Match(item.Value);
                    string hrefResult = attribute.Value;
                    hrefResult = hrefResult.Replace("href=\"", "").Replace("\"", "");
                    if (!urlDictionary.ContainsKey(_morning))
                    {
                        urlDictionary.Add(_morning, hrefResult);
                    }
                }
            }

            string morningURL = urlDictionary[true];
            string launchURL = urlDictionary[false];

            WebClient morningClient = new WebClient();
            morningClient.DownloadStringAsync(new Uri(string.Format("{0}{1}", BaseUrl, morningURL)));
            morningClient.DownloadStringCompleted += morningClient_DownloadStringCompleted;

            WebClient launchClient = new WebClient();
            launchClient.DownloadStringAsync(new Uri(string.Format("{0}{1}", BaseUrl, launchURL)));
            launchClient.DownloadStringCompleted += launchClient_DownloadStringCompleted;

        }

        void launchClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            LaunchCallback(getMenuFromPage(e.Result));
        }

        void morningClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            MorningCallback(getMenuFromPage(e.Result));
        }

        private List<string> getMenuFromPage(string PageHTML)
        {
            List<string> result = new List<string>();
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(PageHTML);
            foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//table[@id='jevents_body']//ul//li"))
            {
                result.Add(link.InnerText);
            }
            return result;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            txtLunch.Text = " Hold on ...";
            txtMorning.Text = " Hold on ...";

            getMenu(DateTime.Today, true, (result) =>
            {
                StringBuilder sb = new StringBuilder();
                foreach (string item in result)
                {
                    sb.Append(item);
                    sb.Append(" - ");
                }
                txtMorning.Text = sb.ToString();
            }, (lunchResult) =>
            {
                StringBuilder sb = new StringBuilder();
                foreach (string item in lunchResult)
                {
                    sb.Append(item);
                    sb.Append(" - ");
                }
                txtLunch.Text = sb.ToString();
            });
        }
    }
}